<!-- 产品信息管理 -->
<template>
  <ContainerSlot>
    <template slot="categoryBar">
      <CategoryBar :categoryList="categoryList" :routerIndex="routerIndex" @categoryBar="categoryBar" />
    </template>
    <template slot="searchModule">
      <SearchForm :labelWidth="'120px'" :formConfig="formConfig" :formData="formData" :slotList="slotList" ref="ruleForm">
        <template slot="searchBtn">
          <el-button type="primary" @click.prevent="search()">查询</el-button>
        </template>
        <template slot="resetBtn">
          <el-button @click.prevent="resetForm()">重置</el-button>
        </template>
      </SearchForm>
    </template>
    <template slot="operationModule">
      <el-button class="optBtn" type="primary" plain @click="add">
        <i class="el-icon-circle-plus-outline"></i>
        添加
      </el-button>
    </template>
    <template slot="contentModule">
      <div v-loading="loading" style="height: 100%;">
        <div class="prod-box">
          <div class="prod-card" v-for="item, index in proList" :key="index">
            <div class="header">
              <el-image class="elImage" v-for="ite, i in item.imgList.slice(0, 3)" :key="i"
                style="width: calc(100% / 3 - 15px); height: 140px;margin-left:10px ;margin-top: 10px;background: #3acaeed7;border: 1px solid #3acaee;"
                :src="ite.productImgUrl" :preview-src-list="item.imgSrcList">
              </el-image>
            </div>
            <div class="content">
              <div class="pro-info">
                <span class="pro-name" @click="loadProDetail(item)" style="flex: 2; margin-right: 30px;">
                  <span class="line">产品名称：</span>
                  <span class="info">{{ item.productName }}</span>
                </span>
                <span>
                  <span class="line">发布日期：</span>
                  <span class="info">{{ item.createTime.substring(0, 10) }}</span>
                </span>
              </div>
              <div class="pro-info">
                <span>
                  <span class="line">产品品牌：</span>
                  <span class="info">{{ item.brand }}</span>
                </span>
                <span>
                  <span class="line">产品规格：</span>
                  <span class="info">
                    {{ item.specificationValue }}{{ item.specificationValueUnit }}/{{ item.specificationUnit }}
                  </span>
                </span>
                <span>
                  <span class="line">产品型号：</span>
                  <span class="info">{{ item.model }}</span>
                </span>
              </div>
              <div class="pro-introd">
                <span class="line">产品介绍：</span>
                <span class="introd">{{ item.description }}</span>
              </div>
            </div>
            <div class="btn">
              <el-button class="opt" type="primary" plain @click="handleEdit(item)">
                <i class="el-icon-edit-outline"></i>
                编辑
              </el-button>
              <el-button class="opt" type="danger" plain @click="handleDelete(item)">
                <i class="el-icon-delete"></i>
                删除
              </el-button>
            </div>
          </div>
          <div class="noData" v-show="proList.length == 0">
            暂无数据
          </div>
        </div>
      </div>

      <el-dialog :close-on-click-modal='false' :title="dialogTitle + '产品'" :visible.sync="dialogFormVisible"
        :before-close="cancel" width="60%">
        <el-form ref="addForm" label-position="right" :model="addForm" class="el-form" :rules="rules" label-width="120px">
          <el-form-item label="产品标题:" prop="productName" class="w50p">
            <el-input v-model="addForm.productName" clearable :disabled="nowChanceStau == 'detail'" />
          </el-form-item>
          <el-form-item label="产品分类:" prop="typeId" class="w50p">
            <el-select v-model="addForm.typeId" clearable placeholder="" :disabled="nowChanceStau == 'detail'">
              <el-option v-for="item in categoryList" :label="item.name" :value="item.value"
                :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品品牌:" class="w50p" prop="brand">
            <el-input v-model="addForm.brand" clearable :disabled="nowChanceStau == 'detail'" />
          </el-form-item>
          <el-form-item label="产品型号:" class="w50p" prop="model">
            <el-input v-model="addForm.model" clearable :disabled="nowChanceStau == 'detail'" />
          </el-form-item>
          <el-form-item label="产品规格:" prop="specificationValue" class="w50p flex" style="font-size: 0;">
            <el-input v-model="addForm.specificationValue" clearable type="number" min="0"
              onkeyup="value=value.replace(/\-/g, '')" style="width: 100%;" :disabled="nowChanceStau == 'detail'" />
            <el-form-item style="margin-bottom: 0;" prop="specificationValueUnit">
              <el-select v-model="addForm.specificationValueUnit" clearable placeholder=""
                :disabled="nowChanceStau == 'detail'" style="width:100%">
                <el-option v-for="item, index in unitList" :key="index" :label="item.unitName"
                  :value="item.unitName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="margin-bottom: 0;width: 100%;" prop="specificationUnit">
              <el-select v-model="addForm.specificationUnit" clearable placeholder=""
                :disabled="nowChanceStau == 'detail'" style="width: 100%;">
                <el-option v-for="item, index in unitList" :key="index" :label="item.unitName"
                  :value="item.unitName"></el-option>
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="规格描述:" class="w50p flex" style="font-size: 0;">
            <el-input v-model="addForm.specDesc" type="string" clearable :disabled="nowChanceStau == 'detail'"
              placeholder="例：请以实际规格为准" />
            <el-select v-model="addForm.specDescDisplay" clearable placeholder="" :disabled="nowChanceStau == 'detail'"
              style="width:30%">
              <el-option label="展示" :value="true"></el-option>
              <el-option label="不展示" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品介绍:" class="w100p">
            <el-input v-model="addForm.description" type="textarea" :rows="6" clearable
              :disabled="nowChanceStau == 'detail'" />
          </el-form-item>
          <el-form-item label="产品图片:" class="w100p" prop="imgUrlList">
            <Upload ref="uploadImg" :urlList="addForm.imgUrlList" :disabled="nowChanceStau == 'detail'"
              @getFile="getFile"></Upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save">
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
    <template slot="footerModule">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        background :page-size="pageSize" :page-sizes="[10, 20, 30]" layout=" prev, pager, next, jumper" :total="total">
      </el-pagination>
    </template>
  </ContainerSlot>
</template>

<script>
import ContainerSlot from '@/components/Container'
import SearchForm from '@/components/Form'
import CategoryBar from "@/components/CategoryBar"
import Upload from "@/components/Upload"

import productTypeApi from "@/api/breed-aquatics-popular/product-library/product-sort-management"
import productApi from "@/api/breed-aquatics-popular/product-library/product-info-management"
import UnitsManagement from '@/api/module/units-management' //单位

export default {
  name: '',
  components: { ContainerSlot, SearchForm, CategoryBar, Upload },
  data () {
    return {
      categoryList: [],
      routerIndex: 0,
      loading: false,
      // 搜索栏表单配置
      formConfig: [
        {
          label: '产品名称',
          prop: 'productName',
          type: 'input',
          width: '150px'
        },
        {
          label: '发布日期',
          prop: 'date',
          type: 'daterange',
          width: '240px'
        }
      ],
      //插槽
      slotList: [{
        slotName: 'searchBtn'
      },
      {
        slotName: 'resetBtn'
      }],
      // 表单数据
      formData: {
        productName: '',
        date: [],
        specificationValue: ''
      },
      // 添加
      dialogFormVisible: false,
      dialogTitle: '',
      nowChanceStau: '',
      addForm: {},
      rules: {
        imgUrlList: [
          { required: true, message: '请上传产品图片', trigger: ['change', 'blur'] },
        ],
        productName: [
          { required: true, message: '请输入产品标题', trigger: ['change', 'blur'] },
        ],
        typeId: [
          { required: true, message: '请输入产品分类', trigger: ['change', 'blur'] },
        ],
        brand: [
          { required: true, message: '请输入产品品牌', trigger: ['change', 'blur'] },
        ],
        model: [
          { required: true, message: '请输入产品型号', trigger: ['change', 'blur'] },
        ],
        specificationValueUnit: [
          { required: true, message: '请选择单位', trigger: ['change', 'blur'] },
        ],
        specificationUnit: [
          { required: true, message: '请选择单位', trigger: ['change', 'blur'] },
        ],
        specificationValue: [
          { required: true, message: '请输入规格', trigger: 'change' },
          {
            validator (_, value, callback) {
              if (value <= 0) {
                callback(new Error('商品规格不小于0'))
              } else {
                callback()
              }
            }
          }
        ], //基础单位对应值
      },
      unitList: [],
      // 产品数据
      proList: [],
      // 分页
      total: 0,
      currentPage: 1,
      pageSize: 2,
    }
  },
  watch: {
    dialogFormVisible (v) {
      if (v) {
        this.$nextTick(() => {
          this.$refs.addForm.clearValidate()
        })
      }
    }
  },
  mounted () {
    this.loadUnit()
    this.loadCategoryList()
  },
  methods: {
    categoryBar (item) {
      this.productTypeId = ''
      if (item.mark === 'status') this.productTypeId = item.value
      this.currentPage = 1
      this.queryPageList()
    },
    // 单位
    loadUnit () {
      UnitsManagement.queryByCondition({}).then(res => {
        this.unitList = res.data
      })
    },
    // 搜索
    search () {
      this.currentPage = 1
      this.queryPageList()
    },
    resetForm () {
      this.$refs.ruleForm.resetForm()
      this.search()
    },
    // 产品分类
    loadCategoryList () {
      productTypeApi.queryByCondition({
        productTypeName: ''
      }).then(res => {
        this.categoryList = res.data.map((el, i) => {
          return { id: i + 1, mark: 'status', name: el.productTypeName, value: el.productTypeId }
        })
      })
    },
    // 搜索
    queryPageList () {
      this.loading = true
      productApi.queryPageByCondition({
        page: this.currentPage,
        size: this.pageSize,
        condition: {
          productName: this.formData.productName || '',
          typeId: this.productTypeId,
          beginTime: this.formData.date && this.formData.date[0] && this.formData.date[0] + ' 00:00:00',
          endTime: this.formData.date && this.formData.date[1] && this.formData.date[1] + ' 23:59:59'
        }
      }).then(res => {
        let { data } = res
        data.content.forEach(dataInfo => {
          if (dataInfo && dataInfo.imgList && dataInfo.imgList.length) {
            dataInfo.imgSrcList = []
            dataInfo.imgList.forEach(item => {
              dataInfo.imgSrcList.push(item.productImgUrl)
            });
          }
        })
        this.proList = data.content
        console.log(this.proList)
        this.total = data.totalElements
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleCurrentChange (e) {
      this.currentPage = e
      this.queryPageList()
    },
    handleSizeChange (e) {
      this.pageSize = e
      this.queryPageList()
    },
    getFile (fileList) {
      console.log(fileList)
      this.$set(this.addForm, 'imgUrlList', fileList)
      // this.addForm.imgUrlList = fileList
    },
    // 详情
    loadProDetail (row) {
      this.addForm = { ...row }
      this.addForm.imgUrlList = this.addForm.imgList.map(el => { return { name: el.productImgUrl, url: el.productImgUrl } })
      this.openDialog('detail')
    },
    // 添加
    add () {
      this.openDialog('add')
    },
    handleEdit (row) {
      this.addForm = { ...row }
      this.addForm.imgUrlList = this.addForm.imgList.map(el => { return { name: el.productImgUrl, url: el.productImgUrl } })
      this.openDialog('edit')
    },
    // 删除
    handleDelete (row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      }).then(() => {
        productApi.del({
          id: row.productId
        }).then(res => {
          if (res.code == 200) {
            this.$message.success("删除成功！")
            this.queryPageList()
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    openDialog (type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    cancel () {
      this.$refs.uploadImg && this.$refs.uploadImg.clearFile()
      this.$refs.uploadImg && (this.$refs.uploadImg.uploadFileList = [])
      this.dialogFormVisible = false;
      this.addForm = {};
    },
    save () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          this.addForm.imgList = this.addForm.imgUrlList.map(el => { return { productImgUrl: el.url } })
          productApi[this.nowChanceStau](this.addForm).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.cancel()
              this.queryPageList()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.flex {

  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-left: 0;
  }
}

.prod-box {
  display: flex;
  flex-wrap: wrap;
  height: 100%;
  overflow: auto;

  .noData {
    width: 100%;
    margin-top: 30px;
    text-align: center;
    font-size: 16px;
  }

  .prod-card {
    width: calc(50% - 10px);
    height: 100%;
    min-height: 420px;
    background: #edf7ff;
    border: 1px solid #b3d9fe;
    border-radius: 8px;
    overflow: hidden;

    &:nth-child(2n+1) {
      margin-right: 20px;
    }

    .header {
      height: 180px;
      overflow: hidden;

      .elImage {}
    }

    .content {
      height: calc(100% - 240px);
      padding: 20px;
      background: #fff;

      &>div {
        margin-bottom: 15px;

        .pro-name {
          color: #329eef;
          font-weight: bold;
          cursor: pointer;
        }

        &.pro-info {
          display: flex;

          &>span {
            width: 33%;
            flex: 1;
            margin-right: 15px;
            display: flex;

            .line {
              width: 84px;
            }

            .info {
              width: calc(100% - 84px);
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            &:last-child {
              margin: 0;
            }
          }
        }

        &.pro-introd {
          line-height: 26px;
          display: flex;
          height: calc(100% - 60px);

          &>span {
            &.introd {
              flex: 1;
              min-height: 80px;
              margin-left: 4px;
              overflow: hidden;
              // display: -webkit-box;
              // text-overflow: ellipsis;
              // -webkit-line-clamp: 4;
              // -webkit-box-orient: vertical;
            }

            &.line {
              &::before {
                top: 3px;
              }
            }
          }
        }

        &>span {
          display: inline-block;
          text-align: left;
        }

        .line {
          position: relative;

          &::before {
            content: '';
            display: inline-block;
            width: 2px;
            height: 20px;
            background-color: #329eef;
            position: absolute;
            left: -10px;
          }
        }
      }
    }

    .btn {
      text-align: right;
      padding: 15px;
    }
  }
}
</style>
